// UserOrderController.java
package com.itheima.controller;

import com.itheima.Service.UserOrderService;
import com.itheima.pojo.*;
import com.itheima.utils.BaseContext;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RestController
@RequestMapping("/api/user/orders")
public class UserOrderController {

    @Autowired
    private UserOrderService userOrderService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 用户分页查询自己的订单
     */
    @GetMapping
    public Result page(UserOrderQueryParam queryParam, HttpServletRequest request) {
        // 从JWT中获取用户ID
//        Integer userId = jwtUtils.getUserIdFromToken(request);
        Integer userId = BaseContext.getCurrentId();
        log.info("用户{}分页查询订单：{}", userId, queryParam);
        queryParam.setUserId(userId); // 设置用户ID
        return Result.success(userOrderService.page(queryParam));
    }

    /**
     * 用户查询订单详情
     */
    @GetMapping("/{id}")
    public Result get(@PathVariable Integer id, HttpServletRequest request) {
//        Integer userId = jwtUtils.getUserIdFromToken(request);
        Integer userId = BaseContext.getCurrentId();
        log.info("用户{}查询订单详情，ID：{}", userId, id);
        
        return Result.success(userOrderService.get(userId, id));
    }

    /**
     * 用户创建订单
     */
    @PostMapping
    public Result create(@RequestBody OrderCreateParam createParam, HttpServletRequest request) {
//        Integer userId = jwtUtils.getUserIdFromToken(request);
        Integer userId = BaseContext.getCurrentId();
        log.info("用户{}创建订单：{}", userId, createParam);
        
        return Result.success(userOrderService.create(userId, createParam));
    }

    /**
     * 用户取消订单
     */
    @PutMapping("/{id}/cancel")
    public Result cancel(@PathVariable Integer id, HttpServletRequest request) {
//        Integer userId = jwtUtils.getUserIdFromToken(request);
        Integer userId = BaseContext.getCurrentId();
        log.info("用户{}取消订单，ID：{}", userId, id);

        try {
            userOrderService.cancel(userId, id);
        } catch (Exception e) {
            return Result.error("当前订单不能直接取消，请点击售后申请退款！");
        }
        return Result.success();
    }

    /**
     * 用户确认收货
     */
    @PutMapping("/{id}/confirm")
    public Result confirm(@PathVariable Integer id, HttpServletRequest request) {
//        Integer userId = jwtUtils.getUserIdFromToken(request);
        Integer userId = BaseContext.getCurrentId();
        log.info("用户{}确认收货，ID：{}", userId, id);

        try {
            userOrderService.confirm(userId, id);
        } catch (Exception e) {
            return Result.error("当前订单未完成，不能确认收货！");
        }
        return Result.success();
    }

    /**
     * 用户申请退款
     */
    @PutMapping("/{id}/refund")
    public Result refund(@PathVariable Integer id, @RequestBody RefundApplyParam applyParam, HttpServletRequest request) {
//        Integer userId = jwtUtils.getUserIdFromToken(request);
        Integer userId = BaseContext.getCurrentId();
        log.info("用户{}申请退款，ID：{}，原因：{}", userId, id, applyParam.getReason());
        
        userOrderService.applyRefund(userId, id, applyParam);
        return Result.success();
    }

    /**
     * 毕设专用：模拟支付（直接修改订单为已付款）
     */
    @PostMapping("/{id}/pay") // 前端调用此接口发起支付
    public Result pay(@PathVariable Integer id, HttpServletRequest request) {
         Integer userId = BaseContext.getCurrentId();

        log.info("用户{}发起支付，订单ID：{}", userId, id);

        try {
            // 调用服务层修改订单状态
            userOrderService.payOrder(userId, id);
            return Result.success("支付成功，订单已更新为已付款状态");
        } catch (Exception e) {
            log.error("支付失败", e);
            return Result.error("支付失败：" + e.getMessage());
        }
    }

    public Result selectOrdersListById(){
        Integer userId = BaseContext.getCurrentId();
        log.info("用户{}查询订单列表", userId);
        return Result.success(userOrderService.selectOrdersListById(userId));
    }
}